package pub.tbc.rubbish.client;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import pub.tbc.rubbish.client.factory.ObjectFactory;
import pub.tbc.rubbish.client.registry.Registry;
import pub.tbc.rubbish.client.util.IPHelper;
import pub.tbc.rubbish.client.util.ServiceHelper;

import java.util.List;

/**
 * 使用Spring 提供的InitializingBean进行初始化，该实现将在spring 容器加载完成后调用
 *
 * @author tbc on 2016/12/6 14:06:44.
 */
@Slf4j
@Component
public class WebAppBootstrap implements InitializingBean {
    private final String DEFAULT_DISCOVERY_PREFIX = "rubbish.discovery.";

    private void register() {
        log.info("register...");
        // IPv4 Address
        String serviceAddress = getServiceAddress();
        // service list
        List<String> services = getServices();

        Registry registry = ObjectFactory.getRegistry();
        // 遍历服务接口，将每一个接口注册到服务中心
        services.forEach(service -> registry.register(service, serviceAddress));
    }

    private List<String> getServices() {
        ServiceHelper serviceHelper = new ServiceHelper();
        return serviceHelper.getServices();
    }

    private String getServiceAddress() {
        IPHelper ipHelper = new IPHelper();
        return ipHelper.getIPv4();
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("rubbish framework stating ...");
        register();
    }
}
